﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Xml;
using Aulac.Global.Enums;
using Aulac.Global.Data;
using Aulac.Global.Common;
using Aulac.Global.Xml;
using Aulac.Rsc.Ems;
using Aulac.Rsc.Ems.Tags;
using Aulac.Client.Data.Helper;
using Aulac.Verb.Ems;
using Aulac.Global.AccessRight;
using Aulac.Rsc;
using Aulac.Client.Global.Interface;
using Aulac.Client.Ems.WinForm.Store.DataFiles;
namespace Aulac.Client.Ems.WinForm.Stores
{
    partial class FormRecMdnStore
    {
        //private string mVchName = "";
        private bool mIsCheckInstock = false;

        #region Override Methods        
        public override void OnFormLoad()
        {
            try
            {
                base.OnFormLoad();
                InitGrd();                
                //cbPrvd.SetCollectionsObjTypes(ObjectTypes.None, ObjectTypes.Khac, ObjectTypes.KHOAPHONG, ObjectTypes.NCC, ObjectTypes.NKPKCB, ObjectTypes.TRAMYTE);

                //Aulac.Client.Data.Ems.Helper.DataItems.DataRscFncHelper.LoadDataRscFnc(cbRscFnc, 1, RscFncTypes.VP);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
      
        protected override bool OnShowDetailVoucher()
        {           
            base.OnShowDetailVoucher();
            if (ValueHelper.isEmpty(mVoucherID) || (grdInfo.SelectedGridRowView == -1))
            {
                if (grdInfo.SelectedGridRowView != -1)
                    Aulac.UtilityTools.MsgBox.Show("Vui lòng chọn một dòng ở [Danh sách] để hiển thị chi tiết !", Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            XmlDataDocument xmlDoc = DataMngStoreHelper.GetVchInputStore(mVoucherID, mVchType);
            XmlElement eHeader = XmlProcess.GetVchHeaderElm(xmlDoc);
            XmlNodeList listNode = XmlProcess.GetListVchLineItem(xmlDoc);
            foreach (Aulac.Client.Global.Interface.IAulacValueDataCtrl ctr in GetListControlsOnForm())
                try
                {
                    if(!(ctr is Aulac.Client.Controls.Ems.ComboBo.ComboObjByTypeCtrl))
                        ctr.SetValueToControl(eHeader);
                }
                catch{}
            ObjectTypes oType = (ObjectTypes)ValueHelper.ChangeType(XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.PartTypeID), typeof(ObjectTypes));
            if (oType == ObjectTypes.None)
            {
                oType = ObjectTypes.NCC;
                cbPrvd.ComboObjectTyeps.ClearDataContainer();
            }
            cbPrvd.ComboObjectTyeps.ObjTypeID = oType;
            string sObjPrkID = XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.PartPrkID);
            if (!ValueHelper.isEmpty(sObjPrkID))
                cbPrvd.ObjPrkID = sObjPrkID;
            grdLine.AddDataToControl(listNode);
            for (int i = 1; i < grdLine.grdData.Rows.Count; i++)
                grdLine.grdData.SetValueCell(i, tagVch.Inv.PriceInExc, grdLine.grdData.GetValueDataCell(i, tagVch.Inv.PriceBuyInExc));
            mVchName = XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.VchName);
            grdLine.SetTotalSummary();
            return true;
        }

        protected override void OnAddNewVoucher()
        {
            this.grdLine.ClearValueTtAmt();
            if (cboRscFunds.IsEmptyDataInList)
                cboRscFunds.ReLoadDataToControl();
            if (cbPrvd.ComboObjectTyeps.IsEmptyDataInList)
                cbPrvd.ComboObjectTyeps.ReLoadDataToControl();
            if (cbRecvPsn.IsEmptyDataInList)
                cbRecvPsn.ReLoadDataToControl();
            if (cbStore.IsEmptyDataInList)
                cbStore.ReLoadDataToControl();
            if (cbTagStoreType.IsEmptyDataInList)
                cbTagStoreType.ReLoadDataToControl();
            txtNo.Text = GetNewVchNo(ref mVchName);
            if (ValueHelper.isEmpty(mVchName))
                mVchName = Aulac.Client.Data.Ems.Helper.VchHelper.GetVchNameOnServer(mVchType);
            cbTagStoreType.TagStoreTypeID = TagStoreTypes.InputBuy;
            cboRscFunds.RscFundsPrkID = "2";
            this.Text = mVchName;
            txtNo.Focus();
        }

        protected override void OnEditVoucher()
        {
            mIsCheckInstock = true;
            base.OnEditVoucher();
            if (cbPrvd.ComboObjectTyeps.IsEmptyDataInList)
                cbPrvd.ComboObjectTyeps.ReLoadDataToControl();
            txtNo.Focus();
        }

        protected override bool OnBeginSaveVoucher()
        {
            grdLine.grdData.EndEditingRow(false);
            //grdLine.grdData.RemoveAllRowsByColEmpty( tagItems.Item.ItemID, tagVch.Inv.Quantity);
            if (cbTagStoreType.IsEmptyValue)
            {
                Aulac.UtilityTools.AulacMsg.Show(Aulac.Client.Ems.WinForm.Stores.Lang.AulacLangMsg.GetMsg(Aulac.Client.Ems.WinForm.Stores.Lang.AulacCodes.ErrAlEmsCMS001));
                cbTagStoreType.Focus();
                return false;
            }
            if (cbStore.IsEmptyValue)
            {
                Aulac.UtilityTools.AulacMsg.Show(Aulac.Client.Ems.WinForm.Stores.Lang.AulacLangMsg.GetMsg(Aulac.Client.Ems.WinForm.Stores.Lang.AulacCodes.ErrAlEmsCMS002));
                cbStore.Focus();
                return false;
            }
            if (grdLine.grdData.Rows.Count == 0)
            {
                Aulac.UtilityTools.AulacMsg.Show(Aulac.Client.Ems.WinForm.Stores.Lang.AulacLangMsg.GetMsg(Aulac.Client.Ems.WinForm.Stores.Lang.AulacCodes.ErrAlEmsCMS003));
                grdLine.Focus();
                return false;
            }
            int iCount = grdLine.ReadOnly == true ? grdLine.grdData.Rows.Count : grdLine.grdData.Rows.Count - 1;
            for (int i = 1; i < iCount; i++)
            {
                int mQuantity = (int)ValueHelper.ChangeType(grdLine.grdData.GetValueDataCell(i, grdLine.ColumnsGrd.Quantity), typeof(int));
                string sItemID =(string)ValueHelper.ChangeType(grdLine.grdData.GetValueDataCell(i, grdLine.ColumnsGrd.ItemID), typeof(string));
                if (mQuantity == 0 || sItemID == null)
                {
                    if (mQuantity == 0)
                        Aulac.UtilityTools.MsgBox.Show(string.Format("Số lượng dòng [ {0} ] không được bằng không !", i), Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        Aulac.UtilityTools.MsgBox.Show(string.Format("Mã y tế ở dòng [ {0} ] đang rỗng !", i), Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    grdLine.grdData.SelectedIndexGridRow = i;
                    return false;
                }                
            }
            return true;
        }

        protected override bool OnSaveVoucherData(ref XmlDataDocument xmlData)
        {
            return SaveRecMdnStore(FormMode, ref xmlData);
        }

        protected override bool OnDeleteDataVoucher()
        {
            try
            {
                mIsCheckInstock = true;
                XmlDataDocument xmlDoc = CreateXmlDocument(AulacEmsVerb.MngStore.RecStore.DelVchRecStore, AulacEmsVerb.MngStore.RecStore.Noun.RecvStore);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchRecInvPrkID, mVoucherID);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchTypeID, mVchType);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.IsCheckQtyLost, mIsCheckInstock);

                ProcessRequest(xmlDoc);
                return true;
            }
            catch (Exception ex)
            {
                Aulac.Global.Exceptions.AulacException x = new Aulac.Global.Exceptions.AulacException(ex);
                if (ErrCodes.ErrorCode.Error0010.Equals(x.ErrorCode))
                {
                    XmlNodeList lst = XmlProcess.GetListVchLineItem(x.XmlEcexption);
                    foreach (XmlElement eLine in lst)
                    {
                        DataRow row = grdLine.AulacDataGrid.GetFirstDataRowByKey(tagVch.Inv.ItemPrkID, XmlProcess.GetValueAtrb(eLine, tagVch.Inv.ItemPrkID));
                        DataTableProcess.SetValueDataRow(row, tagVch.Inv.OverInstock, true);
                    }
                    return false;
                }
                else throw ex;

            }
        }

        protected override void OnSetStateControls(FormModes pFormMode)
        {
            base.OnSetStateControls(pFormMode);
            bool isReadOnly = false;
            if (pFormMode == FormModes.NewMode || pFormMode == FormModes.EditMode)
                isReadOnly = false;
            else
                isReadOnly = true;
            foreach (Aulac.Client.Global.Interface.IAulacStateCtrl ctr in GetListControlsOnForm())
            {
                ctr.FormMode = pFormMode;
                ctr.Enabled = !isReadOnly;
                ctr.ReadOnly = isReadOnly;
            }
            grdLine.FormMode = pFormMode;
        }

        protected override void OnClearValueControls()
        {
            base.OnClearValueControls();
            foreach (Aulac.Client.Global.Interface.IAulacValueDataCtrl ctr in GetListControlsOnForm())
                ctr.ClearValueControls();
            grdLine.ClearDataContainer();
            grdLine.ClearValueTtAmt();
        }

        protected override void OnSetAccessRight(AccessRights accRight)
        {
            base.OnSetAccessRight(accRight);
            if (!accRight.IsAdministrator)
                txtNo.Enabled = false;
            else
                txtNo.Enabled = true;
        }

        protected override void OnRefreshList()
        {
            XmlDataDocument xmlDoc = CreateXmlDocument(AulacEmsVerb.MngStore.RecStore.GetListVchRecStore, AulacEmsVerb.MngStore.RecStore.Noun.RecvStore);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchDateFrom, dtVchFromDate.ShortDate);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchDateTo, dtVchToDate.ShortDate);
            grdInfo.ClearDataContainer();

            DataHelper.GetDataFromServerToControl(grdInfo, xmlDoc);
        }

        protected override void OnPrintVoucher()
        {
            Aulac.Client.Reports.Ems.VchPrints.RptVchPrint.ShowReport(GetValueToXml(), DataFileInfos.FolderFileRpt, DataFileInfos.VchRecStoreName);
        }
        #endregion

        #region Private Methods
        private void Init()
        {
            mVchType = VchTypes.VchRecvMdnStore;
            FieldVchPrkID = tagVch.Inv.VchRecInvPrkID;
            grdInfo.DataSource = new Aulac.Client.Data.Ems.DataSet.StoreMngs.ViewVchRecInvDataTable();
            grdLine.ShowHideColumn(false, grdLine.ColumnsGrd.ItemGrpID);
            grdLine.ListMdnGrpTypes = new List<ItemGrpTypes>() { ItemGrpTypes.GrpDrug, ItemGrpTypes.GrpEquMdn, ItemGrpTypes.GrpFlood, ItemGrpTypes.GrpMdnMaterials, ItemGrpTypes.GrpTradMdn };
            cbPrvd.SetCollectionsObjTypes(ObjectTypes.None, ObjectTypes.TRAMYTE, ObjectTypes.OBJNKPKCB, ObjectTypes.NCC, ObjectTypes.KHOAPHONG);


            cbTagStoreType.SetParamTagStoreTypes(
                    TagStoreTypes.InputBuy,
                    TagStoreTypes.InputOfProgram,
                    TagStoreTypes.InputOther,
                    TagStoreTypes.InputRepair,
                    TagStoreTypes.InputOfClinic
                    );

            cbRecvPsn.ArrPsnTypeID = new List<PsnTypes> { PsnTypes.Instock, PsnTypes.Accounting, PsnTypes.Clinical };
            cbStore.SetStoreTypes(StoreTypes.Buseniss, StoreTypes.Program, StoreTypes.Other, StoreTypes.Manager);
            cbRecvPsn.LoadDataToControl();
        }
        private void InitGrd()
        {
            grdInfo.ClearColumsShow();
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Số CT", ColName = tagVch.Inv.VchNo, DisplayIndex = 0 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Ngày CT", ColName = tagVch.Inv.VchDate, DisplayIndex = 1 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Kí hiệu", ColName = tagVch.Inv.VchSign, DisplayIndex = 2 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Số VAT", ColName = tagVch.Inv.VchTaxNo, DisplayIndex = 3 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Ngày VAT", ColName = tagVch.Inv.VchTaxDate, DisplayIndex = 4 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Nhà cung cấp", ColName = tagVch.Inv.PartName, DisplayIndex = 5 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Người giao", ColName = tagVch.Inv.RelsPsnName, DisplayIndex = 6 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Quản lý kho", ColName = tagVch.Inv.PsnInStockName, DisplayIndex = 7 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Nguồn nhập", ColName = tagItems.Store.TagStoreTypeName, DisplayIndex = 8 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Thuế xuất", ColName = tagVch.Inv.TaxRateH, DisplayIndex = 9 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Kho nhập", ColName = tagVch.Inv.StoreRecName, DisplayIndex = 10 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Nguồn quỹ", ColName = tagItems.RscFnc.RscFundsName, DisplayIndex = 11 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Diễn giải", ColName = tagVch.Inv.Note, DisplayIndex = 12 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Tổng tiền", ColName = tagVch.Inv.AmtSumInExc, DisplayIndex = 13 });            
        }
        private void SetFieldMember()
        {
            txtNo.FieldMember = tagVch.Inv.VchNo;
            txtNote.FieldMember = tagVch.Inv.Note;
            txtTaxNo.FieldMember = tagVch.Inv.VchTaxNo;
            txtSign.FieldMember = tagVch.Inv.VchSign;
            txtTaxRateH.FieldMember = tagVch.Inv.TaxRateH;
            dtTaxDate.FieldMember = tagVch.Inv.VchTaxDate;
            dtVchDate.FieldMember = tagVch.Inv.VchDate;

            cbPrvd.RemoveFieldMappingAll();
            cbPrvd.AddFieldMapping(tagItems.Obj.ObjID, tagVch.Inv.PartTypeID);
            cbPrvd.AddFieldMapping(tagItems.Obj.ObjPrkID, tagVch.Inv.PartPrkID);
            cbPrvd.AddFieldMapping(tagItems.Obj.ObjName, tagVch.Inv.PartName);

            //cbPrvd.AddFieldMapping(tagItems.Prvd.PrvdPrkID, tagVch.Inv.PartPrkID);
            //cbPrvd.AddFieldMapping(tagItems.Prvd.PrvdID, tagVch.Inv.PartID);
            //cbPrvd.AddFieldMapping(tagItems.Prvd.PrvdName, tagVch.Inv.PartName);
            //cbPrvd.AddFieldMapping(tagItems.Prvd.PrvdAddr, tagVch.Inv.PartAddr);
            //cbPrvd.AddFieldMapping(tagItems.Prvd.PrvdDelegate, tagVch.Inv.PartDelegate);

            cbRecvPsn.RemoveFieldMappingAll();
            cbRecvPsn.AddFieldMapping(tagItems.Psn.PsnPrkID, tagVch.Inv.PsnInStockPrkID);
            cbRecvPsn.AddFieldMapping(tagItems.Psn.PsnName, tagVch.Inv.PsnInStockName);

            txtPsnRelsName.FieldMember = tagVch.Inv.RelsPsnName;
            cbTagStoreType.AddFieldMapping(tagItems.Store.TagStoreTypeID, tagVch.Inv.TagStoreTypeID);
            cboRscFunds.AddFieldMapping(tagItems.RscFnc.RscFundsPrkID, tagVch.Inv.RscFundsPrkID);
        }
        private void ShowDetialData(XmlDataDocument xmlDoc)
        {
            XmlElement eHeader = XmlProcess.GetVchHeaderElm(xmlDoc);

            foreach (Control ctr in GetListControlsOnForm())
                if (ctr is Aulac.Client.Global.Interface.IAulacValueDataCtrl)
                    ((Aulac.Client.Global.Interface.IAulacValueDataCtrl)ctr).SetValueToControl(eHeader);

            cbTagStoreType.SetValueToControl(eHeader);
            cbStore.SetValueToControl(eHeader);

            XmlNodeList nodeList = XmlProcess.GetListVchLineItem(xmlDoc);
            grdLine.AddDataToControl(nodeList);
        }
        private void SetAmtTotal()
        {
            //txtTtlAmtLine.Double = grdLine.grdData.SumColum(this.grdLine.ColumnsGrd.AmtLineInExc);
            //txtTtlTax.Double = grdLine.grdData.SumColum(this.grdLine.ColumnsGrd.AmtTaxLineInExc);
        }
        private List<IAulacDataControl> GetListControlsOnForm()
        {
            List<IAulacDataControl> mListControl = null;
            GetListAulacDataControls(ref mListControl, grpParner);
            GetListAulacDataControls(ref mListControl, pnlVch);
            //mListControl.AddRange(new Aulac.Client.Global.Interface.IAulacDataControl[] { cbTagStoreType, cbStore, txtNote, txtTaxRateH });
            GetListAulacDataControls(ref mListControl, pnl);
            return mListControl;
        }

        private XmlDataDocument GetValueToXml()
        {
            XmlDataDocument xmlDoc = CreateXmlDocument("", "");
            if (this.TaskWorking == TaskWorks.Priting)
            {
                XmlElement eHeader = XmlProcess.AddVchHeaderElm(ref xmlDoc);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.RelsPsnName, txtPsnRelsName.Text);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.PsnInStockName, cbRecvPsn.PsnName);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.VchNo, txtNo.Text);
                XmlProcess.SetAtrb(ref eHeader, tagVch.Inv.VchDate, dtVchDate.Text);
                XmlProcess.SetAtrb(ref eHeader, tagItems.Store.StoreName, cbStore.StoreName);

                XmlElement eVLines = XmlProcess.AddVchLinesElm(ref xmlDoc);
                ((IAulacDataContainerCtrl)grdLine).GetDataToChildNodeXml(eVLines);
            }
            return xmlDoc;
        }
        #endregion
    }
}
